package io.renren.wh.order.controller;

import com.alibaba.fastjson.JSONObject;
import io.renren.common.utils.R;
import io.renren.common.utils.RedisUtils;
import io.renren.wh.channel.entity.ChannelConfigEntity;
import io.renren.wh.common.Constant;
import io.renren.wh.order.entity.OrderInfoEntity;
import io.renren.wh.order.enums.OrderStatusEnum;
import io.renren.wh.order.service.OrderInfoService;
import io.renren.wh.order.util.GroovyUtil;
import io.renren.wh.order.util.HttpRequestParamUtil;
import io.renren.wh.order.util.ResponseInfoUtil;
import io.renren.wh.order.vo.PayVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.script.Invocable;
import javax.script.ScriptException;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Map;

@Api(value = "支付接口", tags = {"支付接口"})
@RestController
@RequestMapping("/wh/order")
public class OrderController {
    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    /**
     * 下单
     * @param vo
     * @return
     */
    @ApiOperation(value = "下单接口", notes = "下单接口", httpMethod = "POST")
    @PostMapping(value = "/pay")
    public R pay(@Valid @RequestBody PayVo vo, BindingResult result) {

        if (result.hasErrors()) {
            return R.error("参数效验未通过");
        }
        //下单
        try {
            ResponseInfoUtil responseInfoUtil = orderInfoService.createOrderInfo(vo);
            return R.ok(responseInfoUtil.getData());
        } catch (Exception e){
            return R.error(e.getMessage());
        }

    }

    /**
     * 回调
     * @return
     */
    @PostMapping(value = "/notify")
    public Object notify(HttpServletRequest request) {
        Map<String, String> params = HttpRequestParamUtil.commonHttpRequestParamConvert(request);

        //适配参数内容
        System.out.println(params);

        //从响应内容中查找订单号
        String orderNo = "";
        for (Object obj: params.values()) {
            try{
                if (redisTemplate.hasKey(Constant.CHANNEL_CONFIG+obj.toString())){
                    orderNo =  obj.toString();
                    break;
                }
            } catch (Exception ex){
                continue;
            }
        }

        if (StringUtils.isEmpty(orderNo)){
            return R.error("无此订单");
        }

        //从redis中拿出 订单号对应的 通道配置
        String channelConfigJson = redisUtils.get(Constant.CHANNEL_CONFIG+orderNo);

        ChannelConfigEntity channelConfig = redisUtils.fromJson(channelConfigJson,ChannelConfigEntity.class);

        //适配回调内容
        Invocable inv = null;
        boolean verifySuccess = false;
        try {
            inv = GroovyUtil.getInvocable(channelConfig.getScript());

            //从redis中拿订单信息
            String orderJsonStr = redisUtils.get(Constant.ORDER_PREFIX+orderNo);
            if (orderJsonStr == null){
                return inv.invokeFunction("getNotifyReturn", false);
            }
            OrderInfoEntity orderInfo = redisUtils.fromJson(orderJsonStr,OrderInfoEntity.class);
            //订单状态不符
            if (orderInfo.getOrderstatus() != OrderStatusEnum.NO.type){
                return inv.invokeFunction("getNotifyReturn", false);
            }

            //验证订单数据
            verifySuccess = (boolean) inv.invokeFunction("verifyOrder", params,orderInfo,channelConfig);

            if(!verifySuccess){
                return inv.invokeFunction("getNotifyReturn", false);
            }

            //更改订单状态
            orderInfo.setOrderstatus(OrderStatusEnum.YES.type);
            orderInfoService.orderSuccess(orderInfo);

            //开启回调商户任务
            orderInfoService.createCallBackTask(orderInfo);

            return inv.invokeFunction("getNotifyReturn", true);
        } catch (ScriptException e) {
            e.printStackTrace();
            return R.error("通道配置有误");
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
            return R.error("通道配置有误");
        }  catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

    /**
     * 模拟通道下单
     * @param jsonObject
     * @return
     */
    @PostMapping(value = "/channelPay")
    public Object channelPay(@RequestBody JSONObject jsonObject) {
        System.out.println(jsonObject);
        return 1;
    }
}
